import { View, Swiper, SwiperItem } from '@tarojs/components'
import { AtGrid, AtNoticebar } from 'taro-ui';
import HomeCard from '@/components/HomeCard';
import Taro from '@tarojs/taro';
import { useEffect, useState } from 'react';
import { getCategories, getServiceCategory } from '@/api/home';
import "./index.scss";
import { getAnnounce } from '@/api/announce';

export default function Index() {

  const [categoryList, setCategoryList] = useState<CategoryList[]>([]);
  const [serviceCategoryList, setServiceCategoryList] = useState<ServiceCategoryList[]>([]);
  const [announce, setAnnounce] = useState<string>("");

  useEffect(() => {
    const fetchCategories = async () => {
      const { data } = await getCategories()
      setCategoryList(data);
    }

    const fetchServiceCategory = async () => {
      const { data } = await getServiceCategory();
      setServiceCategoryList(data);
    }

    const fetchAnnounce = async () => {
      const {data} = await getAnnounce();
      setAnnounce(data);
    }

    fetchCategories();
    fetchServiceCategory();
    fetchAnnounce();
  }, [])

  const gridData = categoryList.map(category => ({
    id: category.id,
    image: category.image,
    value: category.category,
  }));

  const propsArr: HomeCardProps[] = serviceCategoryList.map(serviceCategory => ({
    categoryId: serviceCategory.categoryId,
    title: serviceCategory.categoryName,
    product: serviceCategory.serviceList.map(service => ({
      serviceId: service.serviceId,
      pic: service.pic,
      price: service.lowestPrice,
      title: service.serviceName
    }))
  }))

  const handleTo = (item: { image: string, value: string, id: number }) => {
    Taro.navigateTo({
      url: `/pages/home-more/index?title=${item.value}&id=${item.id}`
    })
  }

  return (
    <View className='bg-gray-100 pb-20'>
      <Swiper
        indicatorColor='#999'
        indicatorActiveColor='#333'
        circular
        indicatorDots
        autoplay
      >
        <SwiperItem>
          <View className='swiperImage1' />
        </SwiperItem>
        <SwiperItem>
          <View className='swiperImage2' />
        </SwiperItem>
        <SwiperItem>
          <View className='swiperImage3' />
        </SwiperItem>
      </Swiper>
      <View>
        <AtGrid className='bg-white' onClick={handleTo} data={gridData} />

      </View>
      <AtNoticebar icon='volume-plus' marquee>
        {announce}
      </AtNoticebar>
      <View className='flex flex-col gap-y-3 my-3 items-center'>
        {
          propsArr.map((item, index) => (
            <HomeCard key={index} props={item} />
          ))
        }
      </View>
    </View >
  )
}
